package com.jxpanda.commons.key;

import com.jxpanda.commons.encrypt.EncryptAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.cert.*;

/**
 * @author Panda
 */
@Slf4j
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class RSAKeyHelper extends KeyHelper {

    public RSAKeyHelper(int keySize) {
        super(EncryptAlgorithm.RSA, keySize);
    }

    public X509Certificate toCertificate(String certificate) {
        return toCertificate(certificate.getBytes(StandardCharsets.UTF_8));
    }

    public X509Certificate toCertificate(byte[] bytes) {
        return toCertificate(new ByteArrayInputStream(bytes));
    }

    /**
     * 读取证书
     * 从输入流中读取
     *
     * @param inputStream 输入流
     */
    public X509Certificate toCertificate(InputStream inputStream) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(inputStream);
            cert.checkValidity();
            return cert;
        } catch (CertificateExpiredException e) {
            throw new RuntimeException("证书已过期", e);
        } catch (CertificateNotYetValidException e) {
            throw new RuntimeException("证书尚未生效", e);
        } catch (CertificateException e) {
            throw new RuntimeException("无效的证书", e);
        }
    }

    public X509Certificate loadCertificate(String certificate) {
        if (isNotFile(certificate)) {
            return toCertificate(certificate);
        } else {
            try (FileInputStream inputStream = loadFile(certificate)) {
                return toCertificate(inputStream);
            } catch (Exception ex) {
                log.error("【CERTIFICATE LOAD ERROR】读取证书失败。", ex);
            }
        }
        return null;
    }

}
